<?php

class Book_Model_DbTable_Book extends Zend_Db_Table_Abstract
{

    protected $_name = 'books';

    public function listAll()
    {
        $query=$this->select();
        $query->from($this->_name,array('id','title','author','price','image'));
        return $query;
    }
    
    public function getBook($id)
    {
        $id = (int)$id;
        $row = $this->fetchRow('id = ' . $id);
        if (!$row) {
            throw new Exception("Could not find row $id");
        }
        return $row->toArray();
    }
    
    public function addBook($author, $title, $price, $image = null)
    {
        $data = array(
            'author' => $author,
            'title' => $title,
            'price' => $price,
            'image' => $image,
        );
        
        $this->insert($data);
    }
    
    public function updateBook($id, $author, $title, $price, $image = null)
    {
        if($image!==null)
        {
            $data = array(
                'author' => $author,
                'title' => $title,
                'price' => $price,
                'image' => $image,
            );
        }
        else
        {
            $data = array(
                'author' => $author,
                'title' => $title,
                'price' => $price,
            );
        }
        
        $this->update($data, 'id = '. (int)$id);
    }
    
    public function deleteBook($id)
    {
        $book= $this->getBook($id);
        if(isset($book['image'])) {
            unlink(APPLICATION_PATH . '/../public/images/'. $book['image']);
        }
        $this->delete('id =' . (int)$id);
    }
}

